'use strict';

var crypto = require('crypto');
var os = require('os');

exports.randomID = function() {
	return crypto.createHash('sha1').update(crypto.randomBytes(20)).digest();
};

/**
 * 解码nodes
 */
exports.decodeNodes = function(data) {
	var nodes = [];
	for (var i = 0; i + 26 <= data.length; i += 26) {
		nodes.push({
			nid : data.slice(i, i + 20),
			address : data[i + 20] + '.' + data[i + 21] + '.' + data[i + 22]+ '.' + data[i + 23],
			port : data.readUInt16BE(i + 24)
		});
	}
	return nodes;
};

/**
 * 编码nodes
 */
exports.encodeNodes = function encodeNodes(nodes) {
    var data = new Buffer(26 * nodes.length),
        offset = 0;

    nodes.forEach(function(node) {
        var ip = node.address.split(/\./g, 4);

        node.id.copy(data, offset);
        for (var i = 0; i < 4; i++) {
            data[i + 20 + offset] = +ip[i];
        }
        data.writeUInt16BE(node.port, 24 + offset);
        offset += 26;
    });

    return data;
};

/**
 * 编码peers
 */
exports.encodePeers = function encodePeers(peers) {
    var data = new Buffer(peers.length * 6),
        offset = 0;

    peers.forEach(function(peer) {
        var ip = peer.address.split(/\./g, 4);

        for (var i = 0; i < 4; i++) {
            data[i + offset] = +ip[i];
        }
        data.writeUInt16BE(peer.port, 4 + offset);

        offset += 6;
    });

    return data;
};

/**
 * 解码peers
 */
exports.decodePeers = function decodePeers(data) {
    var peers = [];

    for (var i = 0; i + 6 <= data.length; i += 6) {
        peers.push({
            address: data[i] + '.' + data[i + 1] + '.' +
                data[i + 2] + '.' + data[i + 3],
            port: data.readUInt16BE(i + 4)
        });
    }

    return peers;
};

/**
 * 本机的全部ip
 */
exports.getLocalIps = function getLocalIps() {
    var ips = [],
        ifaces = os.networkInterfaces();

    Object.keys(ifaces).forEach(function (iface) {
        ifaces[iface].forEach(function (addr) {
            ips.push(addr.address);
        });
    });

    return ips;
};

exports.genNeighborID = function(target, nid) {
	return Buffer.concat([ target.slice(0, 15), nid.slice(15) ]);
};